package com.yihen.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.yihen.dto.GoodsDTO;
import com.yihen.dto.Result;
import com.yihen.mappers.GoodsMapper;
import com.yihen.mappers.UserMapper;
import com.yihen.pojo.Goods;
import com.yihen.service.GoodsService;
import com.yihen.util.IdWorker;
import com.yihen.util.LevelCheck;
import com.yihen.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.yihen.util.Constants.HOT_GOODS;

@Service
@Slf4j
public class IGoodsService implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private UserMapper userMapper;


    @Override
    public Result publishGoods(Goods goods) {
        // 获取发布人id
        Long id = UserHolder.getUser().getUserId();
        if (id == null) {
            return new Result("请先登录！");
        }
        // 生产商品id
        Long goodsId = IdWorker.getId();
        goods.setGoodsId(goodsId);
        // 设置发布人id
        goods.setUserId(id);
        // 初始化点击数
        // 判断是否需要审核
        int categoryId = goods.getCategoryId();
        if (categoryId >= 13 && categoryId <= 16) {
            goods.setStatus("待审核");
            goodsMapper.insertGoods(goods);
            return new Result(false, "请等待审核！");
        }else goods.setStatus("已审核");
        goodsMapper.insertGoods(goods);
        log.info("用户:{} 发布商品-{}",UserHolder.getUser().getUserId().toString(),goods.getGoodsName());
        return new Result(true, "上架成功！");
    }

    @Override
    public Result selectAllGoodsByUserId() {
        Long id = UserHolder.getUser().getUserId();
        List<GoodsDTO> goods = goodsMapper.queryAllGoodsByUserId(id);
        changeDealWay(goods);
        return new Result(true, goods);

    }



    @Override
    public Result deleteGoodsById(Long goodsId) {
        // 发起下架人的权限
        int level_ = UserHolder.getUser().getLevel();
        GoodsDTO goodsDTO = goodsMapper.queryGoodsByGoodsId(goodsId);
        Long userId_goods = goodsDTO.getUserId();
        // 商品发布人权限
        int level = userMapper.queryUserById(userId_goods).getLevel();
        Long userId = UserHolder.getUser().getUserId();
        if (userId_goods.equals(userId)) {
            int i = goodsMapper.deleteGoods(userId, goodsId);
            if (i != 0) {
                log.info("用户:{} 下架商品",UserHolder.getUser().getUserId().toString());

                return new Result(true, "下架成功!");
            } else return new Result("下架失败!");
        } else {
            if (level >= level_) {
                return new Result("权限不够,无法下架该商品!");
            } else {
                int i = goodsMapper.deleteGoods(userId_goods, goodsId);
                if (i != 0) {
                    log.info("用户:{} 下架商品",UserHolder.getUser().getUserId().toString());

                    return new Result(true, "下架成功!");
                } else return new Result("下架失败!");
            }
        }


    }

    @Override
    public Result selectMyGoodsByNameOrGoodsId(int mode, int selectMode,String condition) {

        Long userId = UserHolder.getUser().getUserId();
        int level = UserHolder.getUser().getLevel();
        // 判断是否有权限查询该页面的商品
        if (mode > 2 && level <2) {
            return new Result("权限不够,无法查询!");
        }


        List<GoodsDTO> goodsDTOS = null;
        // 通过id查询
        if (selectMode == 1) {
            try {
                Long goodsId = Long.valueOf(condition);
                if (level==1 &&
                        (goodsDTOS = goodsMapper.queryGoodsByGoodsIdAndUserId(goodsId, userId))!=null
                ){}else goodsDTOS = Arrays.asList(goodsMapper.queryGoodsByGoodsId(goodsId));


            } catch (Exception e) {
                return new Result("请输入正确格式的商品id");
            }
        } else if (selectMode == 2) {
            // 通过名称查询
            if (level==1 &&
                    (goodsDTOS = goodsMapper.queryGoodsByNameAndUserId(condition, userId))!=null
            ){}else goodsDTOS =goodsMapper.queryGoodsByName(condition);

        }
        changeDealWay(goodsDTOS);
         return new Result(true,goodsDTOS);
    }

    @Override
    public Result selectAllGoods(int mode) {
        if (mode == 1) {
            return getAllGoods();
        } else {
            Result result = LevelCheck.levelIsOK(2, "无法管理商品!");
            if (!result.isFlag()) {
                return result;
            } else {
                return getAllGoods();
            }
        }

    }

    @NotNull
    private Result getAllGoods() {
        List<GoodsDTO> goodsDTOS = goodsMapper.queryAllGoods();
        changeDealWay(goodsDTOS);

        return new Result(true, goodsDTOS);
    }

    @Override
    public Result selectGoodsByGoodsId(Long goodsId) {
        GoodsDTO good = goodsMapper.queryGoodsByGoodsId(goodsId);
        if (good.getDealWay().equals("M")) {
            good.setDealWay("金钱交易");
        } else {
            good.setDealWay("以物易物");
        }
        return new Result(true, good);
    }

    @Override
    public Result selectCheckingGoodsByUserId() {
        Long userId = UserHolder.getUser().getUserId();
        List<GoodsDTO> goodsDTOS = goodsMapper.queryCheckingGoodsByUserId(userId);
        changeDealWay(goodsDTOS);
        return new Result(true,goodsDTOS);
    }

    @Override
    public Result selectCheckingGoods() {
        Result result = LevelCheck.levelIsOK(2, "无法审核商品!");
        if (!result.isFlag()) {
            return result;
        }
        List<GoodsDTO> goodsDTOS = goodsMapper.queryCheckingGoods();
        changeDealWay(goodsDTOS);
        return new Result(true,goodsDTOS);

    }

    @Override
    public Result selectCheckingGoodsByGoodsId(int mode, String goodsId) {
        Long id = null;
        try {
             id = Long.valueOf(goodsId);

        } catch (Exception e) {
            return new Result("请输入正确格式的商品id");
        }
        int level = UserHolder.getUser().getLevel();
        Long userId = UserHolder.getUser().getUserId();
        List<GoodsDTO> goodsDTOS = null;
        if (mode == 1) {
            goodsDTOS = goodsMapper.queryCheckingGoodsByUserIdAndGoodsId(userId, id);
        } else if (mode == 2) {
            Result result = LevelCheck.levelIsOK(2, "无法查询待审核商品!");
            if (!result.isFlag()) {
                return result;
            }
           goodsDTOS = goodsMapper.queryCheckingGoodsByGoodsId(id);
        }
        changeDealWay(goodsDTOS);
        return new Result(true,goodsDTOS);
    }

    @Override
    public Result acceptGoods(Long goodsId) {
        Result result = LevelCheck.levelIsOK(2, "无法审核商品!");
        if (!result.isFlag()) {
            return result;
        }
        int i = goodsMapper.updateGoodsStatus("已审核", goodsId);
        log.info("用户:{} 通过商品-{}审核",UserHolder.getUser().getUserId().toString(),goodsId);

        return new Result(true, "审核通过!");
    }

    @Override
    public Result updateGoodsStatus(Long goodsId, String status) {
        int i = goodsMapper.updateGoodsStatus(status, goodsId);
        return new Result(true);
    }


    private static void changeDealWay(List<GoodsDTO> goods) {
        for (GoodsDTO good : goods) {
            if (good.getDealWay().equals("M")) {
                good.setDealWay("金钱交易");
            } else {
                good.setDealWay("以物易物");
            }
        }
    }
}
